<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;

class User extends Model
{
    protected $table = 'users';
    
    // 设置字段信息
    protected $schema = [
        'id' => 'int',
        'username' => 'string',
        'password' => 'string',
        'email' => 'string',
        'real_name' => 'string',
        'avatar' => 'string',
        'status' => 'boolean',
        'last_login_at' => 'datetime',
        'last_login_ip' => 'string',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];
    
    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
    
    // 隐藏字段
    protected $hidden = ['password'];
    
    // 类型转换
    protected $type = [
        'status' => 'boolean',
        'last_login_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];
    
    /**
     * 密码修改器
     */
    public function setPasswordAttr($value)
    {
        return password_hash($value, PASSWORD_DEFAULT);
    }
    
    /**
     * 验证密码
     */
    public function verifyPassword($password)
    {
        return password_verify($password, $this->password);
    }
    
    /**
     * 根据用户名查找用户
     */
    public static function findByUsername($username)
    {
        return self::where('username', $username)
                  ->where('status', true)
                  ->find();
    }
    
    /**
     * 更新最后登录信息
     */
    public function updateLoginInfo($ip)
    {
        $this->last_login_at = date('Y-m-d H:i:s');
        $this->last_login_ip = $ip;
        return $this->save();
    }
    
    /**
     * 获取用户信息（不包含密码）
     */
    public function getUserInfo()
    {
        return [
            'id' => $this->id,
            'username' => $this->username,
            'email' => $this->email,
            'real_name' => $this->real_name,
            'avatar' => $this->avatar,
            'last_login_at' => $this->last_login_at,
            'last_login_ip' => $this->last_login_ip
        ];
    }
} 